﻿using Acb.Core.Extensions;
using Acb.WebApi;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using OAuth.Server.Domain;
using OAuth.Server.OAuth;
using OAuth.Server.OAuth.Stores;
using System;
using System.Security.Cryptography;

namespace OAuth.Server
{
    public class Startup : DStartup
    {
        protected override void MapServices(IServiceCollection services)
        {
            services.AddTransient<AccountRepository>();
            services.AddTransient<ClientRepository>();
            services.AddTransient<ResourceRepository>();
            services.AddTransient<GrantRepository>();

            services.AddTransient<IClientStore, ClientStore>();
            services.AddTransient<IResourceStore, ResourceStore>();
            services.AddTransient<IPersistedGrantStore, PersistedGrantStore>();
            //services.AddTransient<IMessageStore<>>();

            var rsa = new RSACryptoServiceProvider();
            //从配置文件获取加密证书
            rsa.ImportCspBlob(Convert.FromBase64String("SigningCredential".Config<string>()));
            services.AddIdentityServer()
                .AddSigningCredential(new RsaSecurityKey(rsa))
                //.AddDeveloperSigningCredential()
                //.AddInMemoryClients(Constants.Clients)
                //.AddInMemoryApiResources(Constants.Apis)
                //.AddInMemoryIdentityResources(Constants.Identities)
                .AddResourceOwnerValidator<OwnerValidator>()
                .AddProfileService<ProfileService>();
            base.MapServices(services);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public override void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            app.UseHttpsRedirection();

            app.UseStaticFiles();
            app.UseIdentityServer();
            app.UseMvcWithDefaultRoute();
            base.Configure(app, env);
            //InitDatabase().GetAwaiter().GetResult();
        }

        //private static async Task InitDatabase()
        //{
        //    await Constants.Clients.ToDataBase();
        //    await Constants.Apis.ToDataBase();
        //    await Constants.Identities.ToDataBase();
        //    await TestUsers.Users.ToDataBase();
        //}
    }
}
